Skip to content

perf(traceql): structural queries read ids first and run on each shard - #1066

Open
44YHC wants to merge 33 commits into
feat/traceql-nested-setfrom
feat/traceql-drilldown-reads
Open

44YHC wants to merge 33 commits into
feat/traceql-nested-setfrom
feat/traceql-drilldown-reads

Conversation

@44YHC

@44YHC 44YHC commented Oct 31, 2026 •

Copy link
Copy Markdown
Collaborator

Stacked on #1035; merge that first. It merges into #1035 as a merge commit, once the top PRs (#1091, #1092) have merged into it.

Breaking changes

Queries that now fail

  • readonly=1 ClickHouse users on a cluster. Structural TraceQL metrics, autocomplete and compare() fail with code 164 (Cannot modify 'prefer_localhost_replica' setting in readonly mode), and where the read tables skip unavailable shards, so do structural searches and every compare().
    Without prefer_localhost_replica=0, a structural search that succeeds logs no unresolved-trace warning: the warning's probe changes that setting. Each refused probe prints the code 164 error to stdout and resets the reader's connection pool, at most once a minute.
    Set prefer_localhost_replica=0, and skip_unavailable_shards=1 if the read tables skip unavailable shards, in the user's settings, or allow them with CHANGEABLE_IN_READONLY, or use readonly=2. Setting them on the user applies to all of that user's Distributed reads. Over HTTP, also set cancel_http_readonly_queries_on_client_close=1 on the user, so the server stops a read when the reader stops waiting. See ClickHouse access.

Results that change

  • Cross-cluster readers without CLICKHOUSE_READ_CLUSTER. Structural queries and compare() run on each shard of ctx.ClusterName through cluster(...). With a read suffix other than _dist and CLICKHOUSE_READ_CLUSTER unset, they read only the local cluster, with no error, where they used to read every cluster of the read table. The reader logs a warning at start-up naming the setting. With the one-pass metrics PR on top, TraceQL metrics with no spanset operator (&&, ||, structural), scalar filter or by() stage join this list, except that a lone {} still reads all the clusters of the read table for its histogram_over_time() exemplars and, with no custom by label, for its other exemplars and for min_over_time() and max_over_time(). With the lone {} follow-up (perf(traceql): read a lone {} metric's rows as master does #1093) on top, a lone {} reads all the clusters of the read table under a custom by label too: avg, sum, min, max, quantile_over_time and histogram_over_time() read every cluster. The exceptions, which read only the local cluster, are rate(), count_over_time() and exemplars other than histogram_over_time()'s under a custom by label, and the range series of a quantile_over_time() of several levels. Set CLICKHOUSE_READ_CLUSTER on readers. See Requirements.
  • One shard per trace. On a cluster, structural queries assume a trace's spans and attribute rows live on one shard. A split trace loses the relations between its shards' spans. Production placement already does this (see Requirements); it is documented, not detected.

Upgrade notes

  • Set CLICKHOUSE_READ_CLUSTER on cross-cluster readers. See Results that change.
  • Run ClickHouse with MALLOC_CONF=background_thread:true,dirty_decay_ms:1000,muzzy_decay_ms:0 (an environment variable of the server, not a config key). It is required at the default portion budget on 7 GiB nodes for 24h structural metrics, tag values and compare(); without it they can fail with code 241. See ClickHouse memory.
  • GIGAPIPE_TRACEQL_PORTION_SPANS counts per shard. Structural queries count spans in range on each shard and portion by the fullest one; a single node counts as one shard. Its default is 5000000.
  • The ClickHouse analyzer. On a cluster, TraceQL queries need the ClickHouse analyzer: keep enable_analyzer at its default of 1 for the reader's user, including through compatibility.
  • Grants. On a cluster, the reader's user needs SELECT on the database, including the local tables, plus REMOTE ON *.*. Without <secret> in remote_servers, shards run as the cluster's <user>; with it, the initial user must exist on every shard with SELECT.
  • Reader memory. The reader holds the IDs of a TraceQL metrics, compare() or filtered tag autocomplete request: 24 + 8 x spans bytes per trace, uncapped, for the whole request; compare() holds both tables at once. max_result_rows on the reader's user caps the IDs statement and counts traces. With result_overflow_mode=throw a request over it gets a 500; don't use break, which silently returns wrong compare() counts and metrics.
  • Planner plugins: a TracesDataPlugin must provide trace_newest as the last column of its final select on the shard-local path too.

Summary

Structural TraceQL queries (>>, <<, ~, &>>, …) read far fewer table parts and fit in memory at 24h on single node and two shards, including Grafana Traces Drilldown's "Service structure" query (ROOT &>> {kind = server}) || ROOT.

statement 1 (ids)     filter + structural stage ──▶ top-n trace ids (+ span ids)
  clusters:           SELECT … FROM cluster(c, view(<body over local tables>))
                      ORDER BY newest LIMIT n  SETTINGS prefer_localhost_replica=0
statement 2           search data / metrics / compare() / tag values,
                      reading only the ids from external table _search_result
compare() counts      per shard over that shard's traces; the reader sums the counts
  • Two statements: search, metrics, compare() and tag autocomplete first select the matching ids, then read data for those ids only (ids_query.go, one runner for all of them).
  • Structural stage: relations are resolved with one pointer jump per trace, not one self-join per hop.
  • Unresolved traces are skipped on the one-jump walk by the same rule as feat(traceql): evaluate structural operators and the Tempo pipeline on the span tree #1034, and the warning's probe runs on each shard, with trace IDs deduplicated across shards.
  • Per shard: on a cluster, structural statement 1 and compare()'s counts run on each shard over local tables; the coordinator only merges. Non-structural ids statements stay as they were. The portion budget is counted on each shard, and the shard-local path carries the trace_newest rank, so portion merging stays exact.
  • Repeated operand: in X || A where X already reads A (the Drilldown query), A is planned once and its rows are kept by widening the final filter.
  • Start-up warning: a reader whose read suffix isn't _dist and has no CLICKHOUSE_READ_CLUSTER (or no CLUSTER_NAME) logs which queries read only the local cluster and names the setting. It doesn't block start-up, and there is no fallback path. Writer-only instances don't warn.
  • Docs: docs/configuration.md gains Requirements (one shard per trace, the analyzer), ClickHouse memory (MALLOC_CONF, reader IDs, max_result_rows) and ClickHouse access (grants, <secret>, readonly=1), and CLICKHOUSE_READ_CLUSTER links Requirements.

Evidence

  • Search, metrics, compare() and tag golden responses are unchanged by the two-statement plans, single node and two shards. After the merge from feat(traceql): nested-set intrinsics, numbered at write time #1035 the goldens were re-recorded and checked key by key: only the sample= keys (scaled by 1/f) and one p key change, and the skip commit turns error results into results or [].
  • go test ./reader/... with GIGAPIPE_TEST_CLICKHOUSE (and _CLUSTER, _HTTP) passes on 24.9 and 25.3, single node and two shards, native and HTTP, including readonly=1 reader users on search, autocomplete, metrics and compare(). Unresolved traces return results over HTTP (testSearchOverHTTP); the garbled round-limit error no longer arises, because no query raises it.
  • Full e2e on two shards with 25.3, and grid.traceql on two shards with 24.9, pass on the full stack tip.
  • Measured on the full stack tip against master and against this branch, two shards at 7 GiB per node, with MALLOC_CONF on and off: the queries in the review, the Drilldown query, >>, ~, structural rate(), tag values and compare(), and plain compare(). The results stay out of this description and go to the reviewer directly.

Known limits

  • Tree read bound. The ancestry tree read stops one hour after the query's end, with no lower bound. A parent that starts later than that counts as missing: its descendants are cut, so they never match a positive operator and always match a ! one.
  • Duration-only autocomplete and re-sent spans. A duration-only filter is answered in one statement over the attribute rows, with no ids stage. A span re-sent with different durations suggests only the attributes of the copies whose duration passes, so keys can drop out; with && over terms met by different copies, a span can suggest none of its attributes.
  • Tag-value memory at high cardinality. A duration-only tag-value request holds all the range's distinct values of the key at once, on the initiator on a cluster, so a high-cardinality key such as a URL or an id can fail on max_memory_usage.
  • Time-prefixed trace ids in portions. Autocomplete portions are trace_id ranges that assume uniform ids. Ids with a time prefix concentrate in few portions: results stay exact, but memory per portion isn't bounded by the budget.
  • &>> with a root operand reads that operand and its root read twice in a statement.
  • 7-day autocomplete. Structural tag-value autocomplete over 7 days can fail with code 241 at 7 GiB, because the node's memory isn't bounded by the per-portion statement, and structural and other span-filtered tag autocomplete over 7 days can reach the client timeout. Duration-only tag autocomplete returns the same keys as master but takes longer and uses more memory; for duration-only tag values master returned no values on the same query, so there is no like-for-like cost.
  • Single-node full >> walk at the default budget. A slice statement can log code 241 while the request still returns its full result.

Merge Danger

Door: two-way. No schema change; reverting the code restores the old statements.

Blast Radius: traces

Every TraceQL search, metrics, compare() and tag autocomplete request runs two statements. On clusters, structural queries assume one shard per trace (see Requirements) and read only the cluster named by CLICKHOUSE_READ_CLUSTER or CLUSTER_NAME.

44YHC added 12 commits October 30, 2026 14:09
Search runs up to the per-trace spansets and returns them to Go with the
listed span ids. Data reads spans, summaries and selected values for the
ids shipped as the external table _search_result (trace_id, span_id[]),
with plain IN on clusters too, so spansets never reach ClickHouse twice.
Structural and plain searches over fixed traces compare with golden
results captured from the single-statement search; the cluster runs
spread the traces over both shards.
…ments

Statement 1 lists the result span ids by trace into the external table
_search_result (compare()'s selection into _selection_result); statement 2
reads the spans of those ids with plain IN, on clusters too. The ids
statement keeps the sample and the analyzer setting; statement 2 always
runs, also over empty ids.
…ements

Statement 1 lists the result span ids of the query by trace into the
external table _search_result; statement 2 reads the attribute keys or
values of those spans from the attrs table with plain IN, on clusters too.
The ids statement keeps the analyzer setting and is uncapped; statement 2
carries the suggestion limit and does not run over empty ids. Each
complexity portion runs both statements once. A query that selects every
span still reads every key or value in one statement.
The golden pins tag keys and values of name and a for plain, structural,
deep, unresolved, limited and portioned queries, captured on 143cc1b, the
single-statement plan, with single node and two shards agreeing. A
recorder test checks that each portion lists its ids once and reads them
once, and skips the attributes read without ids.
…trace

Every structural operator reads its operand sides, the traces they share and
their parent ids into one _nodes group and resolves ancestry in a single
pointer jump with a per-trace round count. One-hop operators recurse only for
traces with a root and a missing parent. The _edges/_spans/_links/_flags chain
and its reach and resolved CTEs are removed.
On a cluster, the ids statement of a structural search runs whole on every
shard inside cluster('<name>', view(...)) over the local tables, with a
per-shard LIMIT and each trace's newest span as trace_newest; the
coordinator keeps the newest traces of the merged rows. Single-node SQL is
unchanged. The plan context carries the cluster name.

This requires a trace's spans to live on one shard, which writers get by
inserting through the _dist tables; docs/traceql.md states it. The two-shard
search fixtures are seeded by trace instead of by span-id parity.
A `||` whose other side repeats an operand of its structural side plans
the structural operator alone, keeping every row of that operand. The pivot's
trace-id set reads its source rows directly instead of the grouped pivot.
Run ClickHouse with MALLOC_CONF=background_thread:true,dirty_decay_ms:1000,
muzzy_decay_ms:0 and set it on the e2e compose ClickHouse services.

Measured on two shards at 7 GiB per node (aarch64, ClickHouse 25.3), 24h
Drilldown, warm-up plus five back-to-back runs:
- defaults: 1/6 pass; jemalloc keeps the previous run's freed pages, RSS
  starts at 2-4.8 GiB instead of ~0.9 and the 0.9 x 7 GiB cap trips (241)
  at ~3 GB tracked.
- with the env: 6/6 pass, median 7.8 s (default warm-up 9.7 s), RSS peak
  <= 5.04 GiB, tracked unchanged (~3-3.8 GB per node). `>>`, `~` and broad
  queries at 24h stay within +-2.5 % wall, RSS peak 0.5-1.3 GiB lower.
- dirty_decay_ms:1000,muzzy_decay_ms:0 alone passes (median 8.6 s);
  background_thread:true alone does not (2/6).
- memory_worker_correct_memory_tracker: 3/6 (the tracker follows RSS).
  Query-level max_bytes_before_external_group_by/_sort=1e9: 6/6 but +33 %
  wall on every large query.
Metrics, compare() and autocomplete run their structural ids statement
whole on each shard through cluster(view()), with prefer_localhost_replica=0;
the coordinator passes on (trace_id, span_ids) only. The metrics
behaviour fixtures seed by trace through the Distributed tables.
compare() reads the attributes of the baseline traces only and counts
them with IN sets over the baseline and selection spans. On a cluster
the counts run whole on each shard through cluster(view()) with
prefer_localhost_replica=0 over local tables; the coordinator sums the
per-shard counts, then keeps the top values per attribute as before.

@rita7lopes rita7lopes left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Four things before I approve. Line numbers are from 13257f5.

1. Warn when a cross-cluster reader has no CLICKHOUSE_READ_CLUSTER

Shard-local statements run on ctx.ClusterName through cluster(...) (shard_local.go:63). That only follows the read cluster when CLICKHOUSE_READ_CLUSTER is set (tables.go:114). An existing reader with CLICKHOUSE_READ_DIST_SUFFIX=_dist_cross_cluster and no CLICKHOUSE_READ_CLUSTER reads remote regions today, but after upgrading its structural queries and compare() read only the local cluster, with no error.

Please log a warning at startup when the read suffix isn't _dist and CLICKHOUSE_READ_CLUSTER is unset. It should say that structural queries and compare() will read only the local cluster, and name the setting to fix it. Don't block startup, and don't add a fallback path.

2. Document memory in the reader, no code change

readIds holds every returned ID in reader memory, with no limit in that function (ids_query.go:88). Sizing memory is the operator's call, so I'm not asking for a cap or a second path. Please add the reader to the "ClickHouse memory" section of docs/configuration.md, explaining that span IDs are held there during metrics and compare().

If max_result_rows on the reader's ClickHouse user does cap the IDs statement, please confirm that and mention it too.

Also document that compare() on a cluster now goes through cluster(...) and sets prefer_localhost_replica (metrics.go:223, shard_local.go:82), and what access the reader's ClickHouse user needs for that, including in readonly mode.

3. Benchmark the top of the stack too

This PR replaces the metrics path that the benchmark I asked for on #1034 measures, so a #1034 number alone won't show what users get. Please run the same comparison against master on this branch: 24h {} | rate(), {...} | rate() by (...) and quantile_over_time(duration, 0.95), with time and peak memory for both ClickHouse and the reader.

The two-shard numbers in the description used the tuned MALLOC_CONF. Please also post them without it, so operators can see whether it's required.

4. Rebase, and run the full suites

The description says the full e2e suite and the grid didn't run on this branch, and CI here only ran Socket and CLA. Please run both once this is rebased.

The #1034 fixes need to carry through, since this PR rewrites much of structural.go: skipping and logging unresolved traces, and keeping from fixed in complexity portions. Please also recheck the garbled round-limit error over HTTP noted in the description, which that fix may remove.

Accepted, no change needed

  • The one-shard-per-trace requirement: stating it in docs/traceql.md is enough.
  • repeatedOperand only handling X || A: it has a measured benefit for Drilldown, and we can generalise it later.
  • The TracesDataPlugin column change, since nobody uses these hooks.

44YHC added 17 commits November 6, 2026 08:55
Remove ancestryGuard and unresolvedAncestryError. An unresolved row is
unreachable under >>, !>> and the one-hop operators; <<, !<<, &>> and &<<
return nothing from a trace with an unresolved row.

Each unresolved-trace probe runs on each shard over local tables, one row
per shard, and the warning deduplicates the ids across shards.
A custom CLICKHOUSE_READ_DIST_SUFFIX without CLICKHOUSE_READ_CLUSTER leaves
TraceQL structural queries and compare() on the local cluster. The reader
logs that once at start-up, names the setting, and carries on.
Structural queries count spans in range on each shard through onEachShard, so
one row per shard reaches the evaluator and its largest-row rule picks the
fullest shard. A single node counts as one shard; span-only estimates keep their
operand count against the same setting.

The estimate goes through the structural gate, which skips unavailable shards
like the read tables and reports an unsupported server before counting.
The docs state that the default assumes MALLOC_CONF.
A shard failing after another shard returned its row would otherwise leave a
smaller estimate and too few portions.
…quirements

Move what shard-local reads need of a trace's shard into Requirements, with
the analyzer a cluster needs, and link CLICKHOUSE_READ_CLUSTER to it. Restore
the round count under Depth limit and the one-shard reason in the numberer's
cap. Add what readIds holds, what max_result_rows counts and why not break,
the grants with the <secret> rule, and what a readonly=1 user must set. Drop
the measured sizing from ClickHouse memory.
A user with the documented grants and settings in its profile matches the
admin over native and HTTP, for readonly=1 with the settings, with
CHANGEABLE_IN_READONLY and for readonly=2. A user without them gets code 164
naming the setting, the probe still finds cycles, and the connected node gets
the shard statement as a remote query.
Each autocomplete portion is a trace_id range, so tempo_traces reads
narrow by its sort key. The ranges split the ids with a nonzero high half
by that half and the ids with a zero high half (64-bit ids) by the low
half, so the portions partition every stored id and stay balanced.

Every table read of a portioned statement keeps the portion: operands,
the ancestry tree read, root and nested-set reads, pipeline pivots and
the tags/values data stage.
Seeds trace ids spread over both halves of the id space and checks that
portioned tags and values equal the unportioned ones, single node and on
two shards, with every portion's ids and data statements reading a
trace_id range.
44YHC added 4 commits November 9, 2026 02:52
The tree read of tempo_traces reads every partition. Its spans are ancestors of operands in range, so an upper bound of the query end plus one hour keeps them, and a parent starting later than that counts as missing.
A filter that compares only duration or span:duration is decided on each
attribute row, since every row carries the span's duration. Tags and tag
values for such a filter read tempo_traces_attrs_gin directly, with no ids
stage, estimate or portions. A span re-sent with differing durations and
not yet merged suggests only the attributes of the copies that pass.
# Conflicts:
#	reader/tempo/metrics_query.go
#	reader/tempo/metrics_query_test.go
#	reader/traceql/timerange/timerange.go
#	reader/traceql/traceql_transpiler/clickhouse_transpiler/select_tags_planner.go

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants